package com.hliushi.learn.config;

import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author llhuang10
 * @date 2021/8/17 8:54
 */
@Configuration
public class ElasticJobRegistryCenterConfig {

    /**
     * zookeeper端口
     */
    private static final int ZOOKEEPER_PORT = 2181;

    /**
     * zookeeper链接字符串 localhost:2181
     */
    private static final String ZOOKEEPER_CONNECTION_STRING = "cvm-node01:" + ZOOKEEPER_PORT;
    /**
     * 定时任务命名空间
     */
    private static final String JOB_NAMESPACE = "elastic-job-example-java";


    /**
     * zk的配置及创建任务中心
     *
     * @return 用于协调分布式服务的注册中心
     */
    @Bean(initMethod = "init")
    public CoordinatorRegistryCenter setUpRegistryCenter() {
        // zk的配置
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(ZOOKEEPER_CONNECTION_STRING, JOB_NAMESPACE);
        // 减少zk的超时时间
        /**
         * 任务的调度时间为 3 秒一次, 而在这里设置的session超时时间是100毫秒 1s = 1000ms
         * 当断开一个实例连接, 时间超过100ms, 节点在zookeeper就失效了,就会触发分片机制
         * #
         * 如果不配置超时时间, 默认情况下, 断开一个实例, 需要30以上这个节点才能在失效,
         * 节点失效后, 才会触发分片机制, 如果任务调度的间隔时间小于SessionTimeoutMilliseconds
         * 会出现异常分片的任务会丢失
         */
        zookeeperConfiguration.setSessionTimeoutMilliseconds(100);
        // 创建注册中心
        ZookeeperRegistryCenter registryCenter = new ZookeeperRegistryCenter(zookeeperConfiguration);
        registryCenter.init();
        return registryCenter;
    }


}
